package com.zhou.framework.util;

import com.zhou.util.StringTool;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lang.zhou
 * @since 2023/4/9 9:53
 */
public class CamelUtil {
    private static final char UNDERLINE = '_';
    private static final Pattern TO_HUMP_PATTERN = Pattern.compile("[-_]([a-z0-9])");
    private static final Pattern TO_TABLE_PATTERN = Pattern.compile("[A-Z]");

    public static String camel2underline(String param) {
        if (StringTool.isNotBlank(param)) {
            StringBuilder builder = new StringBuilder(param);
            Matcher matcher = TO_TABLE_PATTERN.matcher(param);

            for(int i = 0; matcher.find(); ++i) {
                builder.replace(matcher.start() + i, matcher.end() + i, UNDERLINE + matcher.group().toLowerCase());
            }

            if (UNDERLINE == builder.charAt(0)) {
                builder.deleteCharAt(0);
            }

            return builder.toString();
        } else {
            return "";
        }
    }
}
